import { Body, Delete, Get, HttpException, HttpStatus, Param, Patch, Post, Query } from '@nestjs/common'
import { FindOptionsWhere } from 'typeorm'
import { ListPaginationDto } from '@/shared/types/globalDto.dto'
import { BaseService } from './base.service'

export class BaseController<T, K extends keyof T> {
  constructor(protected readonly service: BaseService<T, K>) {}

  /**
   * 新增数据
   */
  @Post()
  create(@Body() data: T) {
    return this.service.create(data)
  }

  /**
   * 查找数据
   */
  @Get(':id')
  findOne(@Param('id') id: any) {
    return this.service.findOne({ id } as any)
  }

  /**
   * 获取分页数据
   */
  @Get('page')
  findPage(@Query() query: ListPaginationDto & FindOptionsWhere<T>) {
    return this.service.findPage({
      where: query as FindOptionsWhere<T>,
    })
  }

  /**
   * 获取全部数据
   */
  @Get()
  findAll(@Query() query: FindOptionsWhere<T>) {
    return this.service.findAll(query)
  }

  /**
   * 更新数据
   */
  @Patch(':id')
  async update(@Param('id') id: number, @Body() data: Omit<T, K | 'createdAt' | 'updatedAt'>) {
    const findData = await this.service.findOne({})
    if (!findData) {
      throw new HttpException('数据不存在', HttpStatus.NOT_FOUND)
    }
    return this.service.update(id, data as any)
  }

  /**
   * 删除数据
   */
  @Delete(':id')
  delete(@Param('id') id: number) {
    return this.service.delete(id)
  }
}
